package com.example.klinedemo.carame

import android.content.Context
import android.hardware.Camera
import android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK
import android.view.SurfaceHolder
import android.view.SurfaceView

class CarameView(context: Context) : SurfaceView(context), SurfaceHolder.Callback, Camera.PreviewCallback {


    init {
        holder.addCallback(this)
    }

    val camera: Camera by lazy {
        Camera.open(CAMERA_FACING_BACK)
    }

    val size:Camera.Size by lazy {
        val parameters: Camera.Parameters = camera.parameters
        parameters.getPreviewSize()
    }
    val h264Play:H264Play = H264Play(size.width,size.height)

    override fun surfaceCreated(holder: SurfaceHolder) {
        startPreview()
    }

    private fun startPreview() {
        camera.setPreviewDisplay(holder)
        camera.setDisplayOrientation(90)
        val buffer = ByteArray(size.width * size.height * 3 / 2)
        camera.addCallbackBuffer(buffer)
        camera.setPreviewCallbackWithBuffer(this)
        camera.startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }

    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        h264Play.encode()
        h264Play.start(data?:ByteArray(0))

        camera?.addCallbackBuffer(data)
    }


}